#define _CRT_SECURE_NO_WARNINGS

#include"list.h"

void SListInit(SLNode** pphead)
{
	assert(pphead);

	*pphead = (SLNode*)malloc(sizeof(SLNode));
	if (*pphead == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	
	(*pphead)->next = *pphead;
	(*pphead)->prev = *pphead;
}
void Slistdestroy(SLNode** pphead)
{
	assert(pphead);

	SLNode* cur = (*pphead)->next;
	SLNode* next = cur->next;

	while (cur != *pphead)
	{
		free(cur);
		cur = next;
		next = cur->next;
	}

	free(*pphead);
	*pphead = cur = next = NULL;
}

SLNode* SListFind(SLNode* phead, STNodeDataType x)
{
	assert(phead);

	SLNode* cur = phead->next;

	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}

	return NULL;
}
void SListInsert(SLNode* pos, STNodeDataType x)
{
	assert(pos);

	SLNode* posPrev = pos->prev;
	SLNode* newNode = BuyNode(x);

	posPrev->next = newNode;
	newNode->prev = posPrev;
	newNode->next = pos;
	pos->prev = newNode;

}
void SListErase(SLNode* pos)
{
	assert(pos);
	assert(pos->next != pos);
	

	SLNode* posNext = pos->next;
	SLNode* posPrev = pos->prev;

	free(pos);
	pos = NULL;
	posNext->prev = posPrev;
	posPrev->next = posNext;

}

SLNode* BuyNode(STNodeDataType x)
{
	SLNode* newNode = (SLNode*)malloc(sizeof(SLNode));
	if (newNode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}

	newNode->next = NULL;
	newNode->prev = NULL;
	newNode->data = x;

	return newNode;
}

void SlistPrint(SLNode* phead)
{
	assert(phead);

	SLNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}

	printf("\n");
}

void SListPushFront(SLNode* phead, STNodeDataType x)
{
	SListInsert(phead->next, x);
}
void SListPushBack(SLNode* phead, STNodeDataType x)
{
	SListInsert(phead, x);
}
void SlistPopFront(SLNode* phead)
{
	SListErase(phead->next);
}
void SlistPopBack(SLNode* phead)
{
	SListErase(phead->prev);
}